package com.bookstore.controller;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.utils.Json;
import com.bookstore.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginAndRegisterController {
    public final static String USER = "user";
    private final Logger logger = LoggerFactory.getLogger(LoginAndRegisterController.class);
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param user
     * @param request
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@ModelAttribute("user") User user, HttpServletRequest request)throws Exception{
        System.out.println(user.getAccount());
        String message = "";
        if (user.getAccount().equals("") || user.getPassword().equals("")){
            message = "用户名或密码不能为空!";
        }else{
            User dbuser = userService.findUserByAccount(user.getAccount());
            if(dbuser == null){
                message = "该用户未注册!请先注册一个账户";
            }else if (MD5Util.md5(user.getPassword()).equals(dbuser.getPassword())){
                    System.out.println("用户登录userId:"+dbuser.getuId());
                    request.getSession().setAttribute(USER,dbuser);
                    logger.info("用户登录：",dbuser.getAccount());
                    if (dbuser.getType().equals("1")){
                        return "redirect:jsp/index.jsp";
                    }else {
                        return "redirect:layui-admin/index.jsp";
                    }
                }else {
                    message = "密码错误！";
                }
        }
        request.getSession().setAttribute("message",message);
        return "redirect:jsp/login.jsp";
    }

    /**
     * 修改用户信息
     * @param user
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/modify_user",method = RequestMethod.POST)
    public boolean modifyUser(@ModelAttribute("user") User user,HttpServletRequest request){
        User sessionUser = (User) request.getSession().getAttribute(USER);
        user.setuId(sessionUser.getuId());
        String message = "";
        if (userService.updateUser(user)){
            return true;
        }else {
            return false;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Json register(@ModelAttribute("user") User user){
        Json json = new Json();
/*        if (user.getAccount().equals(""))
            message = "注册账户不能为空";
        if (user.getPassword().equals(""))
            message = "设置的密码不能为空";
        if (user.getNickname().equals(""))
            message = "请填写你的用户名";*/
        User dbuser = userService.findUserByAccount(user.getAccount());//查询数据库中时候有该用户
        if (dbuser == null){
            String password = MD5Util.md5(user.getPassword());//对密码进行md5加密
            user.setPassword(password);
            try {
                user.setType("1");
                user.setPhoto("user_default.gif");
                userService.insertUser(user);//数据库中添加用户
                json.setMsg("注册成功，请登录！");
                json.setSuccess(true);
            }catch (Exception e){
                logger.error(e.getMessage());
                e.printStackTrace();
                json.setMsg("注册用户失败，请检查填写信息时候正确");
            }
        }else {
             json.setMsg("该用户名已经被注册");
        }
        return json;
    }
}
